package common

import "net"

func GetLocalIP() (ip string, err error) {
	var (
		addrs   []net.Addr
		addr    net.Addr
		IPNet   *net.IPNet
		isIPNet bool
	)
	//获取所有网卡
	if addrs, err = net.InterfaceAddrs(); err != nil {
		return
	}
	for _, addr = range addrs {
		//IPV4或者V6,addr还有可能类似Unix域套接字的
		if IPNet, isIPNet = addr.(*net.IPNet); isIPNet && !IPNet.IP.IsLoopback() {
			if IPNet.IP.To4() != nil {
				ip = IPNet.IP.String()
				return
			}
		}
	}
	return "", ERR_NO_LOCAL_IP_FOUND
}

func GenHashCode(k string) int {
	if len(k) == 0 {
		return 0
	}
	var hashCode int = 0
	var lastIndex int = len(k) - 1
	for i := range k {
		if i == lastIndex {
			hashCode += int(k[i])
			break
		}
		hashCode += (hashCode + int(k[i])) * 31
	}
	return hashCode
}

func HashCode(job *Job) int {
	value := job.Name + job.Command + job.CronExpr + job.Description
	if len(value) == 0 {
		return 0
	}
	var hashCode int = 0
	var lastIndex int = len(value) - 1
	for i := range value {
		if i == lastIndex {
			hashCode += int(value[i])
			break
		}
		hashCode += (hashCode + int(value[i])) * 31
	}
	return hashCode
}
